let memberData = JSON.parse(sessionStorage.getItem('memberData'));
console.log("doctor_advice memberData:" + memberData);
let yaodianId = 0;
let memberId = 0;
let orderId = 0;
let doctorId = $.cookie("doctorId");
let diagnosisId = "";
let nickName = "";
let headImg = "";
let deptName = "";

if (memberData != null) {
    memberId = memberData.memberId;
    orderId = memberData.orderId;
    diagnosisId = memberData.diagnosisId;
    headImg = memberData.icon;
    nickName = $.cookie("truename");
    deptName = $.cookie("deptName");
    let obj = JSON.parse(sessionStorage.getItem('obj'));
    doctorId = obj.doctorId;
    serverIP = obj.serverIP;
    serverApi = obj.serverApi;
    serverApi3 = obj.serverApi3;
    serverApi1 = obj.serverApi1;
    socketUrl6 = obj.socketUrl6;
}


$(document).ready(function () {

    $(document).click(function (event) {
        var _con1 = $('#chubuZhenduan'); // 设置目标区域
        var _con2 = $('#txSelect'); // 设置目标区域
        if (!_con1.is(event.target) && !_con2.is(event.target) && _con2.has(event.target).length === 0) {
            $('#txSelect').hide();
        }
        var _con3 = $('.kyIptDiv'); // 设置目标区域
        var _con4 = $('#yaoSearch'); // 设置目标区域
        var _con5 = $('#yaoSearchList'); // 设置目标区域
        if (!_con3.is(event.target) && !_con4.is(event.target) && !_con5.is(event.target) && _con5.has(event.target).length === 0) {
            $('#yaoSearchList').hide();
        }
    });

    $("#selectDrugstore").click(function () {
        if (memberData == null) {
            layer.msg("未接通患者")
        } else {
            parent.parent.layer.open({
                type: 2,
                title: '选择药店地址',
                area: ['900px', '500px'],
                // closeBtn: 0,
                shadeClose: true,
                content: 'page/diagnose/select_drugstore_dialog.html',
                end: function () {
                    let pharmacyVO = JSON.parse(sessionStorage.getItem('pharmacyVO'));
                    yaodianId = pharmacyVO.id;
                    // layer.msg(yaodianId)
                    $("#pharmacyVO").text(pharmacyVO.name)
                    //加载历史处方
                    var reqData00 = {memberId: memberId, pharmId: yaodianId};
                    $.ajax({
                        type: "POST",
                        contentType: "application/x-www-form-urlencoded",
                        url: serverApi + "/precord/findHistoricalPrescriptionVO" + "?" + formatParams(reqData00),
                        success: function (result) {
                            if (result.code === 200) {
                                $("#historyChuFangShow").css("display", "")
                                $("#historyChuFang").html('\n' +
                                    '                <tr style="background-color: #E6E6E6;color: #333333;">\n' +
                                    '                    <td width="100px">处方时间</td>\n' +
                                    '                    <td width="150px">药品名称</td>\n' +
                                    '                    <td width="170px">厂家名称</td>\n' +
                                    '                    <td width="60px">规格</td>\n' +
                                    '                    <td width="60px">医生</td>\n' +
                                    '                    <td width="60px">操作</td>\n' +
                                    '                </tr>')

                                $(result.data).each(function (index, item) {
                                    $(item.list).each(function (index, element) {
                                        $("#historyChuFang").append('\n' +
                                            '                <tr>\n' +
                                            '                    <td>' + item.createTime + '</td>\n' +
                                            '                    <td>' + element.name + '</td>\n' +
                                            '                    <td>' + element.hospDrugManuf + '</td>\n' +
                                            '                    <td>' + element.dosage + '*' + element.specifications + '</td>\n' +
                                            '                    <td>' + item.doctorName + '</td>\n' +
                                            '                    <td class="yaosr" sid="' + element.drugsId + '" sname="' + element.name + ' ' + element.specifications + '*' + element.conversionCoefficient + ' ' + element.packing + '" chang="' + element.hospDrugManuf + '" ji="' + element.dosage + '"' +
                                            ' yongfa="' + element.usages + '" packing="' + element.drunit + '" pin="' + element.frequency + '" bao="' + element.packagingUnit + '" stat="有" tj="否" style="color: #1A7DFF;" onclick="selectYao1(this)">引用</td>\n' +
                                            '                </tr>')
                                    })
                                })
                                if (result.data.length === 0) {
                                    $("#historyChuFangShow").css("display", "none")
                                }
                            }
                        }
                    });
                    return false;
                }
            });
        }
    })

    // 点击确定
    $("#confirm2").click(function () {
        var zhusu = $("#input_appeal").val();
        var zheng = $("#txGroup").find("dd");
        var zStr = "";
        if (memberData == null) {
            layer.msg("未接通患者")
        } else if (zhusu == "") {
            layer.msg("请填写主诉");
        } else if (zheng.length < 1) {
            layer.msg("请选择症状");
        } else if (kaiyaoSave()) {
            for (var i = 0; i < zheng.length; i++) {
                var z1 = $(zheng[i]);
                zStr += z1.attr("sid");
                zStr += ",";
            }

            var reqData = {chiefComplaint: zhusu, diagnosticId: zStr, diagnosisId: memberData.roomId};

            $.ajax({
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                url: serverApi + "/omsring/updateUmsMemberDiagnosis" + "?" + formatParams(reqData),
                success: function (result) {
                    if (result.code === "200") {
                        layer.msg("success")
                    }
                },
                error: function (e) {
                    layer.msg("关闭视频提交失败！");
                }
            });

            //选择诊断记录
            // var reqData2 = {chiefComplaint: zhusu, diagnosticId: zStr, diagnosisId: diagnosisId};
            // $.ajax({
            //     type: "POST",
            //     contentType: "application/x-www-form-urlencoded",
            //     url: serverApi + "/omsring/updateUmsMemberDiagnosis" + "?" + formatParams(reqData2),
            //     success: function (result) {
            //         if (result.code === 200) {
            //             toKaiyao();//加载开药div
            //         }
            //     },
            //     error: function (e) {
            //         console.error("关闭视频提交失败！");
            //     }
            // });
            parent.parent.layer.open({
                type: 2,
                title: false,
                area: ['490px', '310px'],
                closeBtn: 0,
                shadeClose: false,
                content: 'remind_dialog.html',
                success: function (layero, index) {
                    var body = parent.parent.layer.getChildFrame('body', index);
                    //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var iframeWin = parent.parent.window[layero.find('iframe')[0]['name']];
                    var date = new Date();
                    if (date.getTime() % 2 === 0) {
                        iframeWin.setMessage("请确认是否立即开具处方？");
                        iframeWin.setConfirm("确定", function () {
                        });
                    } else {
                        iframeWin.setSingleButton();
                        iframeWin.setMessage("本次处方暂未开具药品，无法保存");
                        iframeWin.setConfirm("确定", function () {
                        });
                    }
                }
            });
        }
    });

    $("#cancel").click(function () {
        parent.parent.layer.open({
            type: 2,
            title: false,
            area: ['490px', '310px'],
            closeBtn: 0,
            shadeClose: false,
            content: 'remind_dialog.html',
            success: function (layero, index) {
                var body = parent.parent.layer.getChildFrame('body', index);
                //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                var iframeWin = parent.parent.window[layero.find('iframe')[0]['name']];
                var date = new Date();
                if (date.getTime() % 3 === 0) {
                    iframeWin.setMessage("确定撤回该处方吗？");
                    iframeWin.setConfirm("确定", function () {
                    });
                } else if (date.getTime() % 3 === 1) {
                    iframeWin.setMessage("该处方已完成支付，确定要强制撤回吗？\n撤回后请主动联系该患者");
                    iframeWin.setConfirm("确定", function () {
                    });
                } else {
                    iframeWin.setSingleButton();
                    iframeWin.setMessage("未保存处方，无需撤回");
                    iframeWin.setConfirm("确定", function () {
                    });
                }
            }
        });
    });

    $("#reset2").click(function () {
        window.location.reload()
    });

    var selectMode = 1;
    $('input[type=radio][name=mode]').change(function () {
        var label = $("label.mode-radio");
        label.removeClass("mr-select");
        if (this.value == 1) {
            selectMode = 1;
            $(label[0]).addClass("mr-select");
            $("#select_name").text("已选择单项：")
            $("#hot_name").text("※ 热门单项 ※")
        } else if (this.value == 2) {
            selectMode = 2;
            $(label[1]).addClass("mr-select");
            $("#select_name").text("已选择套餐：")
            $("#hot_name").text("※ 热门套餐 ※")
        }
    });

    $('input[type=radio][name=packageMode]').change(function () {
        var label = $("label.mode-radio");
        label.removeClass("mr-select");
        if (this.value == 1) {
            $("#timePackageLabel").addClass("mr-select");
        } else if (this.value == 2) {
            $("#onePckageLabel").addClass("mr-select");
        }
    });
});

function projectSelectChange(res) {
    if (res == 1) {
        $("#selectDrugstore").show();
        $("#prescription").show();
        $("#technician").hide();
        $("#service").hide();
    } else if (res == 2) {
        $("#selectDrugstore").show();
        $("#prescription").hide();
        $("#technician").show();
        $("#service").hide();
    } else {
        $("#selectDrugstore").hide();
        $("#prescription").hide();
        $("#technician").hide();
        $("#service").show();
    }
}

var serviceSelectList = [];

function serviceSelectChange() {
    var input_select = $("#serviceResult").val();
    var option = $("#serviceList option");
    var option_length = option.length;
    for (var i = 0; i < option_length; i++) {
        var option_value = option.eq(i).attr("value");
        console.log("option_value: ", option_value);
        if (input_select == option_value) {
            // option_id = $("option").eq(i).attr('data-id');
            serviceSelectList.push(option_value);
            break;
        }
    }
}

function onConfirmClick() {
    parent.parent.layer.open({
        type: 2,
        title: false,
        area: ['490px', '310px'],
        closeBtn: 0,
        shadeClose: false,
        content: 'remind_dialog.html',
        success: function (layero, index) {
            var body = parent.parent.layer.getChildFrame('body', index);
            //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var iframeWin = parent.parent.window[layero.find('iframe')[0]['name']];
            var date = new Date();
            iframeWin.setSingleButton();
            iframeWin.setMessage("当前暂无医技项目，无法保存");
            iframeWin.setConfirm("确定", function () {
            });
        }
    });
}

function onSendClick() {
    parent.parent.layer.open({
        type: 2,
        title: false,
        area: ['490px', '310px'],
        closeBtn: 0,
        shadeClose: false,
        content: 'remind_dialog.html',
        success: function (layero, index) {
            var body = parent.parent.layer.getChildFrame('body', index);
            //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            var iframeWin = parent.parent.window[layero.find('iframe')[0]['name']];
            var date = new Date();
            iframeWin.setMessage("请确认是否立即发送服务包？");
            iframeWin.setConfirm("确定", function () {
            });
        }
    });
}


/*** 搜索诊断名称 开始 ***/
var currRow = -1;
var souKeyd = "";

function loadZhenduanList() {
    // layer.msg("loadZhenduanList");
    var txInput = $("#chubuZhenduan").val();
    if (txInput == "") {
        return;
    }
    currRow = -1;
    souKeyd = txInput;
    $(".txRow").remove();
    //$("#txGroup").find("dd").remove();
    var reqData = {name: txInput};
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/omsring/findSmsDiagnosticName" + "?" + formatParams(reqData),
        success: function (result) {
            //alert(JSON.stringify(result));
            var barr = result.data;
            var bstr = "";
            if (barr.length > 0) {
                for (var i = 0; i < barr.length; i++) {
                    bstr += "<div sid='" + barr[i].id + "' class='txRow' onclick='d4(this)'>" + barr[i].name + "</div>";
                }
                $("#txSelect").html("").append(bstr).show();
                currRow = 0;
                if ($(".txRow").length > 0) {
                    $($(".txRow")[currRow]).addClass("curr");
                }
            } else {
                $("#txSelect").html("&nbsp;没有搜索到症状").show();
            }
        },
        error: function (e) {
            console.error("搜索诊断失败！");
        }
    });
}

/***搜索药品***/
function findYaoList() {
    // if (memberData == null) {
    //     layer.msg("未接通患者")
    // return;
    // }
    if (yaodianId == "" || yaodianId == "0" || yaodianId == 0) {
        layer.msg("请先选择药店");
        return;
    }
    $("#yaoSearchList").css("width", "710px").find(".yaosr").remove();
    var reqData = {id: yaodianId, memberId: memberId, name: yaoTmp};
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/precord/findPharmDrugsVOList" + "?" + formatParams(reqData),
        success: function (result) {
            var arr = result.data;
            var str = "";
            if (arr.length > 0) {
                for (var i = 0; i < arr.length; i++) {
                    //药品id  药品名称  厂家信息  用法  剂量 (单位) 频率  天数  数量  状态  药店推荐
                    str += "<div class='yaosr' sid='" + arr[i].id + "' sname='" + arr[i].name + " " + arr[i].specifications + "✕" + arr[i].conversionCoefficient + "" + arr[i].minimumPackagingUnit + "' chang='" + arr[i].hospDrugManuf + "' ";
                    str += " yongfa='" + arr[i].usages + "' ji='" + arr[i].dosage + "' packing='" + arr[i].drunit + "' pin='" + arr[i].frequency + "' ";
                    str += " bao='" + arr[i].packagingUnit + "' stat='有' tj='否' ";
                    str += "onclick='selectYao1(this)'>";
                    str += "<div class='yaos1'>" + arr[i].name + "</div>";
                    str += "<div class='yaos1'>" + arr[i].hospDrugManuf + "</div>";
                    str += "<div class='yaos2'>" + arr[i].specifications + "✕" + arr[i].conversionCoefficient + "" + arr[i].minimumPackagingUnit + "</div>";
                    str += "<div class='yaos3'>" + arr[i].packagingUnit + "</div></div>";
                }
                var yaoSearchList = $("#yaoSearchList");
                yaoSearchList.append(str).show();
                yaoSearchList.find(".yaost").css("width", "710px");
                yaoSearchList.find(".yaosr").css("width", "700px");
            } else {
                $("#yaoSearchList").append("<div class='yaosr'>&nbsp;没有搜索到药品</div>").show();
            }
        },
        error: function (e) {
            console.error("搜索药品失败！");
        }
    });
}

function selectYao1(s) {
    console.log("============")
    console.log(s)
    console.log("============")
    var ss = $(s);
    var has = $(".kaiyaoRow[sid=" + ss.attr("sid") + "]");
    if (has.length > 0) {
        layer.msg("此药品已存在，请勿重复添加");
        return;
    }
    var str = "<div class='kaiyaoRow' sid='" + ss.attr("sid") + "'>";
    str += "<div class='kyv22'>" + ss.attr("sname") + "</div>";
    // str += "<div class='kyv14'>" + ss.attr("chang") + "</div>";
    str += "<div class='kyv12'>";
    str += "<select class='kaiyao-yongfa'>";
    str += "<option value='' selected='selected'>&nbsp;</option><option value='口吸入'>口吸入</option><option value='口服'>口服</option>";
    str += "<option value='口腔用'>口腔用</option><option value='含服'>含服</option><option value='含漱'>含漱</option>";
    str += "<option value='呼吸道给药'>呼吸道给药</option><option value='喷雾吸入'>喷雾吸入</option><option value='喷鼻'>喷鼻</option>";
    str += "<option value='滴眼'>滴眼</option><option value='皮下注射'>皮下注射</option><option value='皮肤外用'>皮肤外用</option>";
    str += "<option value='直肠给药'>直肠给药</option><option value='眼用'>眼用</option><option value='耳用'>耳用</option>";
    str += "<option value='肌注'>肌注</option><option value='舌下含服'>舌下含服</option><option value='阴道给药'>阴道给药</option>";
    str += "<option value='静注'>静注</option><option value='静滴'>静滴</option><option value='鼻用'>鼻用</option>";
    str += "<option value='冲服'>冲服</option>";
    str += "</select>";
    str += "</div>";
    str += "<div class='kyv12'>";
    str += "<div class='kyIptDiv'><input type='text' value='" + ss.attr("ji") + "' class='ky-jiliang'><span class='ky-d'>" + ss.attr("packing") + "</span></div>";
    str += "</div>";
    str += "<div class='kyv16'>";
    str += "<select class='kaiyao-pinlv'>";
    str += "<option value='' selected='selected'>&nbsp;</option><option value='每天一次'>每天一次</option><option value='每晚一次'>每晚一次</option>";
    str += "<option value='每天二次'>每天二次</option><option value='每天三次'>每天三次</option><option value='每天四次'>每天四次</option>";
    str += "<option value='每二小时一次'>每二小时一次</option><option value='每四小时一次'>每四小时一次</option><option value='每六小时一次'>每六小时一次</option>";
    str += "<option value='每八小时一次'>每八小时一次</option><option value='每十二小时一次'>每十二小时一次</option><option value='隔日一次'>隔日一次</option>";
    str += "<option value='每周一次'>每周一次</option><option value='每周二次'>每周二次</option><option value='必要时服用'>必要时服用</option>";
    str += "<option value='紧急时服用'>紧急时服用</option><option value='立即使用'>立即使用</option>";
    str += "</select>";
    str += "</div>";
    str += "<div class='kyv12'>";
    str += "<div class='kyIptDiv'><input type='text' value='1' class='ky-tianshu'>天</div>";
    str += "</div>";
    str += "<div class='kyv12'>";
    str += "<div class='kyIptDiv'><input type='text' value='1' class='ky-shuliang'>" + ss.attr("bao") + "</div>";
    str += "</div>";
    // str += "<div class='kyv9'><span class='color1'>" + ss.attr("stat") + "</span></div>";
    str += "<div class='kyv6 color2'>" + ss.attr("tj") + "</div>";
    str += "<div class='kyv8' style='padding-top: 5px'><img src='../../image/c30.png' class='kaiyaoDel' onclick='deleteKaiyaoRow(this)'/></div>";
    str += "</div>";
    $("#yaoSerInp").before(str);
    var row1 = $(".kaiyaoRow[sid=" + ss.attr("sid") + "]");
    row1.find(".kaiyao-yongfa").val(ss.attr("yongfa"));
    row1.find(".kaiyao-pinlv").val(ss.attr("pin"));
    $("#yaoSearchList").hide();
    updateYaoStat();
}

function deleteKaiyaoRow(s) {
    $(s).parent().parent().remove();
}

var txTmp = "";

function chubuZhenduan(event) {
    console.log("querySelector")
    var txInput = $("#chubuZhenduan").val();
    if (txInput == "") {
        return;
    }
    if (txTmp != txInput) {
        txTmp = txInput;
        loadZhenduanList();
        //shangXia(event);//上下键控制
    }
};
var yaoTmp = "";

function yaoSearch(event) {
    console.log("querySelector")
    var txInput = $("#yaoSearch").val();
    if (txInput == "") {
        return;
    }
    if (yaoTmp != txInput) {
        yaoTmp = txInput;
        findYaoList();
    }
};

function onKeyDown(e) {
    var ev = window.event || e;
    if (ev.keyCode == 13) {
        if (currRow == -1) {
            loadZhenduanList();
        } else {
            if ($("#chubuZhenduan").val() == souKeyd) {
                var bname = $($(".txRow")[currRow]).text();
                var bid = $($(".txRow")[currRow]).attr("sid");
                if ($("dd[sid='" + bid + "']").length == 0 && $(".txRow").length > 0) {
                    $("#txGroup").append("<dd sid='" + bid + "'>" + bname + "<span onclick='d3(this)'>X</span></dd>");
                }
            } else {
                loadZhenduanList();//输入框中文字发生变化，回车时重新搜索
            }
        }
    }
    shangXia(ev);
}

function d3(s) {
    $(s).parent().remove();
}

function d4(s) {
    var bname = $(s).text();
    var bid = $(s).attr("sid");
    if ($("dd[sid='" + bid + "']").length == 0 && $(".txRow").length > 0) {
        $("#txGroup").append("<dd sid='" + bid + "'>" + bname + "<span onclick='d3(this)'>X</span></dd>");
    }
}

function shangXia(ev) {
    if (ev.keyCode == 40) {//向下
        if (currRow >= ($(".txRow").length - 1)) return;
        currRow = currRow * 1 + 1;
        $(".txRow").removeClass("curr");
        $($(".txRow")[currRow]).addClass("curr");
        if (currRow > 2) document.getElementById("txSelect").scrollTop = (currRow - 2) * 30;
    } else if (ev.keyCode == 38) {//向上
        if (currRow == 0) return;
        currRow = currRow * 1 - 1;
        $(".txRow").removeClass("curr");
        $($(".txRow")[currRow]).addClass("curr");
        if (currRow > 2) document.getElementById("txSelect").scrollTop = (currRow - 2) * 30;
        else document.getElementById("txSelect").scrollTop = 0;
    }
}

/*** 搜索诊断名称 结束 ***/

/*** 提交药品订单 ***/
function kaiyaoSave() {
    var kaiyaoList = $(".kaiyaoRow");
    if (kaiyaoList.length < 1) {
        layer.msg("请添加药品！");
        return false;
    }
    var wanzheng = "1";
    for (var i = 0; i < kaiyaoList.length; i++) {
        var row1 = $(kaiyaoList[i]);
        var ky2shuliang = row1.find(".ky-shuliang").val();
        var kaiyao2yongfa = row1.find(".kaiyao-yongfa").val();
        var kaiyao2pinlv = row1.find(".kaiyao-pinlv").val();
        var ky2jiliang = row1.find(".ky-jiliang").val();
        var ky2tianshu = row1.find(".ky-tianshu").val();
        //检查完整
        if (ky2shuliang == "") wanzheng = "0";
        if (kaiyao2yongfa == null || kaiyao2yongfa == "") wanzheng = "0";
        if (kaiyao2pinlv == null || kaiyao2pinlv == "") wanzheng = "0";
        if (ky2jiliang == "") wanzheng = "0";
        if (ky2tianshu == "") wanzheng = "0";
    }
    if (wanzheng == "0") {
        layer.msg("请完整填写药品信息！");
        return false;
    }
    var cuo = 0;
    cuo += shuziCheck(ky2shuliang);
    cuo += shuziCheck(ky2jiliang);
    cuo += shuziCheck(ky2tianshu);
    if (cuo > 0) {
        return false;
    }
    var you = "1";
    var kyv4 = $(".kyv4");
    for (var i = 0; i < kyv4.length; i++) {
        if ($(kyv4[i]).text() == "无") you = "0";
    }
    var tishimark = '提交药品生成处方吗？';
    if (you == "0") {
        tishimark = '所选药品中存在无库存药品！继续提交吗？';
    }
    //eg1
    layer.confirm(tishimark, {icon: 3, title: '系统提示'}, function (index) {
        //do something
        layer.msg("开方中，请稍等..")
        submitYaoPin();

        layer.close(index);
    });
    // $.confirm({
    //     title: '系统提示',
    //     content: tishimark,
    //     confirmButton: '确定',
    //     cancelButton: '取消',
    //     animation: 'scale',
    //     confirmButtonClass: 'btn-primary',
    //     cancelButtonClass: 'btn-danger',
    //     backgroundDismiss: false,
    //     confirm: function () {
    //         submitYaoPin();
    //     },
    //     cancel: function () {
    //
    //     }
    // });

}

function submitYaoPin() {
    var kaiyaoList = $(".kaiyaoRow");
    var yaojson = '[';
    for (var i = 0; i < kaiyaoList.length; i++) {
        var row1 = $(kaiyaoList[i]);
        //拼装json
        yaojson += '{';
        yaojson += '"id":"' + row1.attr("sid") + '",';//药品id
        yaojson += '"num":"' + row1.find(".ky-shuliang").val() + '",';//盒数
        yaojson += '"usages":"' + row1.find(".kaiyao-yongfa").val() + '",';//用法
        yaojson += '"frequency":"' + row1.find(".kaiyao-pinlv").val() + '",';//频率
        yaojson += '"dosage":"' + row1.find(".ky-jiliang").val() + '",';//剂量
        yaojson += '"drunit":"' + row1.find(".ky-d").text() + '",';//最小单位
        yaojson += '"useDays":"' + row1.find(".ky-tianshu").val() + '"';//天数
        yaojson += '}';
        if (i < (kaiyaoList.length - 1)) yaojson += ',';
    }
    yaojson += ']';
    var reqData = {
        doctorId: doctorId,
        drugsList: yaojson,
        memberId: memberId,
        orderId: orderId,
        pharmInspectionId: yaodianId,
        type: 1
    };
    console.log("开药参数：" + JSON.stringify(reqData));
    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        url: serverApi + "/precord/addDrugsOrder" + "?" + formatParams(reqData),
        success: function (result) {
            if (result.code == "200") {
                submitMemberEvent(orderId, "2", "3", doctorId);
                //发送开了处方通知
                loadSocket();
                window.setTimeout(function () {
                    send1();
                    //发送开了处方socket给小程序
                    var content = "患者端收到处方";
                    var message = "#ms12#m" + memberId + "#ms12#d" + doctorId + "#ms12#" + nickName + "#ms12#" + headImg + "#ms12#" + content + "#ms12#" + 15 + "#ms12#" + diagnosisId + "#ms12#";
                    if (!window.WebSocket) {
                        console.error("socket连接失败..");
                        return;
                    }
                    if (socket.readyState == WebSocket.OPEN) {
                        socket.send(message);
                    } else {
                        console.error("socket连接失败请重试..");
                    }
                    $(".kaiyaoRow").remove();

                    //图文还是视频
                    if (sessionStorage.getItem("changeLeft")) {
                        sessionStorage.setItem("twShowChuFangId", orderId)
                    } else {
                    }

                    parent.layer.closeAll();
                    parent.layer.msg("已成功开具处方")
                    window.location.reload()
                }, 900);
            } else {
                layer.msg("提交失败");
            }
        },
        error: function (e) {
            console.error("提交药品订单失败！");
        }
    });
}

function updateYaoStat() {
    var kaiyaoRow = $(".kaiyaoRow");
    for (var i = 0; i < kaiyaoRow.length; i++) {
        var yao1 = $(kaiyaoRow[i]);
        var reqData = {drugsId: yao1.attr("sid"), pharmId: yaodianId};
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            url: serverApi + "/precord/findPharmDrugsByDrugsId" + "?" + formatParams(reqData),
            success: function (result) {
                var res = result.data;
                if (res.rel == "1") {
                    var sd = $(".kaiyaoRow[sid=" + res.drugsId + "]").find(".kyv4");
                    $(sd[0]).html("<span class='color1'>有</span>");
                } else {
                    var sd = $(".kaiyaoRow[sid=" + res.drugsId + "]").find(".kyv4");
                    $(sd[0]).html("<span class='color2'>无</span>");
                }
            },
            error: function (e) {
                console.error("查找药品失败！");
            }
        });
    }
}


/***Socket连接开始***/
var socket = "";

function loadSocket() {
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket(socketUrl6);
        socket.onmessage = function (event) {
            var data = event.data;
            console.log("收到消息：" + data);
            if (data.indexOf("#ms11#") != -1) {
                //收到初始化验证消息
                if (data.indexOf("#dianshi#") != -1) {
                    toXuanzhuan();//小电视旋转270
                } else if (data.indexOf("#teevee#") != -1) {
                    toXZhuanTV();//大电视旋转180
                }
            } else if (data.indexOf("#ms12#") != -1) {
                //收到普通消息
                var res = data.substr(data.indexOf("#ms12#"), data.length).split("#ms12#");
                var name = res[3];
                var head = res[4];
                var content1 = res[5];
                var time = res[res.length - 2];
                var type = res[6];
                if (head == "") head = "image/head1.jpg";
                var str = "";
                if (("d" + doctorId) == res[2]) {
                    //我发出的消息
                    if (type == "5") {
                        str += "<div class='chat-right'>";
                        str += "<div class='chat-right-headimg'><img src='" + headImg + "' sname='" + nickName + "'></div>";
                        str += "<div class='chat-right-time'>" + nickName + "&nbsp;&nbsp;" + time + "</div>";
                        str += "<div class='chat-right-text'>";
                        str += "<i></i><p>您已向 " + $("#merName").text() + " 发送了服务包 <span class=bold onclick='kanchufang()'>【" + content1 + "】</span> 未付费</p>";
                        str += "</div></div>";
                    }
                } else {
                    //对方发给我的消息
                    if (type == "2") {
                        $("#hzxList").prepend("<img src=" + content1 + " class=hzxImg onclick='hzxImgDa(this)'/>");
                    }
                }
                $("#chatList").append(str);
                $("#chatList")[0].scrollTop = $("#chatList")[0].scrollHeight;
            }
        };
        socket.onopen = function (event) {
        };
        socket.onclose = function (event) {
        };
    }
}

function send1() {
    var message = "#ms11#m" + memberId + "#ms11#d" + doctorId + "#ms11#" + diagnosisId + "#ms11#" + nickName + "#ms11#" + deptName + "#ms11#";//验证消息
    if (!window.WebSocket) {
        console.error("socket连接失败.");
        return;
    }
    if (socket != "" && socket.readyState == WebSocket.OPEN) {
        socket.send(message);
    } else {
        console.error("socket连接失败请重试.");
    }
}